﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Downplay.Mechanics.Impulses;
using Orchard.ContentManagement;
using Downplay.Mechanics.Impulses.Services;
using Orchard;
using Downplay.Mechanics.Services;
using Orchard.Environment.Extensions;
using Downplay.Mechanics.Impulses.Defaults;

namespace Downplay.Mechanics.Paperclips
{
    [OrchardFeature("Downplay.Mechanics.Impulses")]
    public class ConnectorImpulseHandler : IImpulseGenerator
    {
        
        private readonly IMechanicsService _mechanics;
        private readonly IEnumerable<IConnectorImpulseGenerator> _connectorImpulseProviders;

        public ConnectorImpulseHandler(
            IOrchardServices services,
            IMechanicsService mechanics,
            IEnumerable<IConnectorImpulseGenerator> connectorImpulseProviders)
        {
            Services = services;
            _mechanics = mechanics;
            _connectorImpulseProviders = connectorImpulseProviders;
        }

        public IOrchardServices Services { get; set; }

        public void Generating(ImpulseDisplayContext context)
        {
        }

        public void Generated(ImpulseDisplayContext context)
        {
        }

        public void Actuating(ImpulseContext context)
        {
            foreach (var cip in _connectorImpulseProviders)
            {
                if (context.Impulse.Prefix == cip.ImpulsePrefix
                    && context.Impulse.Name == cip.ImpulseName)
                {
                    var type = cip.ConnectorType(context);
                    var rightItems = cip.RightContent(context);
                    foreach (var item in rightItems)
                    {
                        var connectors = _mechanics.CreateConnector(context.SourceContent, item, type);
                        // TODO: The impulse handler might not *necessarily* be expecting every type of connector created (inverses etc.).
                        // Need to examine specific use cases for all of this.
                        foreach (var c in connectors)
                        {
                            cip.ConnectorAlteration(context, c);
                        }
                    }
                }
            }
        }

        public void Actuated(ImpulseContext context)
        {
        }
    }
}